<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Utils;

use HyperfExtension\Jwt\Contracts\JwtFactoryInterface;
use HyperfExtension\Jwt\Contracts\JwtSubjectInterface;
use HyperfExtension\Jwt\Contracts\ManagerInterface;
use HyperfExtension\Jwt\Exceptions\JwtException;
use HyperfExtension\Jwt\Jwt;
use HyperfExtension\Jwt\Payload;

class JwtUtil
{
    /**
     * 提供了对 JWT 编解码、刷新和失活的能力。
     */
    protected ManagerInterface $manager;

    /**
     * 提供了从请求解析 JWT 及对 JWT 进行一系列相关操作的能力。
     */
    protected Jwt $jwt;

    public function __construct(
        ManagerInterface $manager,
        JwtFactoryInterface $jwtFactory
    )
    {
        $this->manager = $manager;
        $this->jwt = $jwtFactory->make();
    }

    public function issued(JwtSubjectInterface $user): string
    {
        return $this->jwt->fromUser($user);
    }

    /**
     * @throws JwtException
     */
    public function getPayload(): Payload
    {
        return $this->jwt->parseToken()->getPayload();
    }
}
